//
//  DLEmoticonViewController.swift
//  01 表情键盘
//
//  Created by danli on 15/12/27.
//  Copyright © 2015年 danli. All rights reserved.
//

import UIKit

class DLEmoticonViewController: UIViewController {
    
    // 传入textView
    weak var textView: UITextView?
    init(textView:UITextView)
    {
        self.textView = textView
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // 懒加载数据模型
    lazy var emoticonPages:[DLEmoticonPage] = {
        return DLEmoticonPage.emoticonPages
    }()
    
    var layout:UICollectionViewFlowLayout?
    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
    }
    
    func prepareUI()
    {
        view.addSubview(collectinView)
        view.addSubview(toolBar)
        
        //添加约束
        collectinView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        // 使用VFL来添加约束
        // 给collectinView添加约束
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView":collectinView]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolBar(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView":collectinView, "toolBar": toolBar]))
        
        // 给toolBar添加约束
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["toolBar" : toolBar]))
        
        prepareToolBar()
        prepareCollectionView()
    }
    
    
    let reuserIdentify = "reuserIdentify"
    func prepareCollectionView()
    {
        collectinView.backgroundColor = UIColor(white: 0.8, alpha: 1)
        collectinView.dataSource = self
        collectinView.delegate = self
        collectinView.registerClass(CZEmoticonCell.self, forCellWithReuseIdentifier: reuserIdentify)
    }
    
    
    // 每个view的tag值默认为0, 加一个初始值才不会导致出现错误
    let baseTag = 1000
    func prepareToolBar()
    {
        var tag = baseTag + 0
        var items = [UIBarButtonItem]()
        
        // 添加工具条的按钮项
        for page in emoticonPages
        {
            let title = page.group_name_cn
            let btn = UIButton()
            btn.setTitle(title, forState: UIControlState.Normal)
            btn.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
            btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
            btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted)

            btn.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
            btn.sizeToFit()
                        
            // 当btn是工具条的第一个按钮时，选中
            if tag == baseTag + 0
            {
                switchSelectedBtn(btn)
            }
            
            btn.tag = tag
            // 添加点击事件
            btn.addTarget(self, action: "tabBarBtnDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
            items.append(UIBarButtonItem(customView: btn))
            
            // 添加拉伸弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            tag++
        }
        items.removeLast()
        toolBar.items = items
    }
    
    /// 当点击表情键盘下方的按钮时调用
    func tabBarBtnDidClick(btn:UIButton)
    {
        // 获取按钮的tag值
        let tag = btn.tag - baseTag
        collectinView.selectItemAtIndexPath(NSIndexPath(forRow: 0, inSection: tag), animated: true, scrollPosition: UICollectionViewScrollPosition.Left)
        
        // 切换当前按钮的选中状态
        switchSelectedBtn(btn)
    }
    
    /// 标记当前被选中的按钮
    var selectedBtn:UIButton?
    
    /// 切换选中的按钮
    func switchSelectedBtn(btn:UIButton)
    {
        selectedBtn?.selected = false
        btn.selected = true
        selectedBtn = btn
    }
    
    lazy var collectinView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: CZCollectionViewFlowLayout())
    
    
    // MARK: - 懒加载
    // 在懒加载的时候布局没有任何作用，因为此时collectionView还没完成约束，对其布局没有作用
//    lazy var collectinView:UICollectionView = {
//        
//        let layout = UICollectionViewFlowLayout()
//        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
//        collectionView.dataSource = self
//        layout.minimumInteritemSpacing = 0
//        layout.minimumLineSpacing = 0
//        
//        collectionView.backgroundColor = UIColor.blueColor()
//        
//        layout.itemSize = CGSize(width: collectionView.frame.width / 7, height: collectionView.frame.height / 3)
//        
//        
//        // 滚动方向
//        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
//        
//        collectionView.pagingEnabled = true
//        collectionView.bounces = false
//        collectionView.showsHorizontalScrollIndicator = false
//        return collectionView
//    }()
    
    lazy var toolBar:UIToolbar = {
        let toolBar = UIToolbar()
        toolBar.backgroundColor = UIColor.lightGrayColor()
        toolBar.backgroundColor = UIColor.lightGrayColor()
        return toolBar
    }()

}

// 创建 UICollectionViewFlowLayout的子类
class CZCollectionViewFlowLayout:UICollectionViewFlowLayout
{
    
    // 这个方法是当collectionView要显示的时候调用，可以在此进行collectionView的布局
    override func prepareLayout() {
        super.prepareLayout()
        
        // 设置每个cell的大小
        let width = (collectionView?.frame.width)! / 7
        let height = (collectionView?.frame.height)! / 3
        itemSize = CGSize(width: width, height: height)
        
        // cell间间距为0
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        
    }
}

extension DLEmoticonViewController: UICollectionViewDataSource, UICollectionViewDelegate
{
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return emoticonPages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emoticonPages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuserIdentify, forIndexPath: indexPath) as! CZEmoticonCell
        
        cell.emoticon = emoticonPages[indexPath.section].emoticons[indexPath.row]
        
        return cell
    }
    
    /// 当停止拖拽的时候调用
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let indexPath = collectinView.indexPathsForVisibleItems()[10]
        
        // 将对应于当前组的按钮选中
        // 获取toolBarButton
        let btn = toolBar.viewWithTag(indexPath.section + baseTag) as! UIButton
        switchSelectedBtn(btn)
    }
    
    // 当选中某个表情的时候调用
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticonPage = emoticonPages[indexPath.section]
        let emoticon = emoticonPage.emoticons[indexPath.item]
        
       
        if let textView = self.textView
        {
            textView.insertEmoticon(emoticon)
        }
        
        // 添加最近使用的表情
        // 若使用的是最近表情包的表情，则不需要添加最近使用表情
        if indexPath.section != 0
        {
            DLEmoticonPage.addLatelyEmoticon(emoticon)
//            print(DLEmoticonPage.emoticonPages[0].emoticons)
//            print(DLEmoticonPage.emoticonPages[0].emoticons.count)
            
//            collectionView.reloadSections(NSIndexSet(index: 0))
        }
    }
}
